<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    title="流程表单权限配置"
    width="60%"
    @ok="handleSubmit"
  >
    <div class="content">
      <Collapse v-model:activeKey="activeKey">
        <CollapsePanel v-for="(node, idx) in nodeList" :key="idx">
          <template #header>
            <label class="flex items-center">
              <div class="min-w-18">节点名称:</div>
              <Input v-model:value="node.nodeName" placeholder="请输入节点名称" />
            </label>
          </template>
          <CommonConfig :isAction="false" :columns="formSchema" :data="node.flowFormPermissions" />
        </CollapsePanel>
      </Collapse>
    </div>
    <div class="actions mt-12">
      <a-button @click="handleAdd">新增</a-button>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import CommonConfig from '../CommonConfig.vue';
  import { Collapse, Input } from 'ant-design-vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { mockItem, formSchema } from './data';

  import { saveFormFieldAuthApi, getFormFieldAuthApi } from '/@/api/config-center/model-design';

  export default defineComponent({
    name: 'TenantModal',
    components: {
      BasicModal,
      Collapse,
      CollapsePanel: Collapse.Panel,
      Input,
      CommonConfig,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const activeKey = ref(0);
      let id = '';
      const nodeList = ref<Recordable[]>([mockItem]);
      const { createMessage } = useMessage();
      let fieldList: Recordable[] = [];
      const [registerModal, { setModalProps, closeModal, changeLoading }] = useModalInner(
        async ({ schemas = [], modelId }: { schemas: Recordable[]; modelId: string }) => {
          changeLoading(true);
          fieldList = cloneDeep(schemas);
          id = modelId;

          const ret = await getFormFieldAuthApi(modelId);
          console.log(
            '%cret===>63： ',
            'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
            ret,
          );

          nodeList.value = ret || [mockItem];
          for (const node of nodeList.value) {
            if (!node.modelId) {
              node.modelId = modelId;
            }
            if (node.flowFormPermissions.length) {
              fieldList.forEach((f, idx) => {
                const info = node.flowFormPermissions.find((el) => el.field === f.field);
                if (info) {
                  fieldList[idx] = info;
                }
              });
            }

            node.flowFormPermissions = cloneDeep(fieldList);
          }
          changeLoading(false);
        },
      );

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          const params = unref(nodeList);

          if (!params.length) {
            createMessage.warning('请添加权限');
            return;
          }
          const emptyNode = params.findIndex((el) => !el.nodeName);

          if (emptyNode !== -1) {
            createMessage.error(`第${emptyNode + 1}行 节点名称不能为空`);
            return;
          }
          const apiFn = saveFormFieldAuthApi;
          await apiFn(id, params);
          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function handleAdd() {
        nodeList.value.push({
          nodeName: undefined,
          flowFormPermissions: cloneDeep(fieldList),
        });
      }
      return {
        activeKey,
        nodeList,
        formSchema,
        registerModal,
        handleSubmit,
        handleAdd,
        // treeData,
      };
    },
  });
</script>
